package com.woniu.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.order.feign.CouponsSeckillFeignClient;
import com.woniu.order.pojo.Coupons;
import com.woniu.user.mapper.UserCouponsMapper;
import com.woniu.user.pojo.UserCoupons;
import com.woniu.user.service.IUserCouponsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户优惠卷中间表 服务实现类
 * </p>
 *
 * @author LiFangyu
 * @since 2023-02-15
 */
@Service
public class UserCouponsServiceImpl extends ServiceImpl<UserCouponsMapper, UserCoupons> implements IUserCouponsService {

    @Autowired(required = false)
    private UserCouponsMapper userCouponsMapper;

    @Autowired
    private CouponsSeckillFeignClient couponsSeckillFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void asyncDbToRedis() {
        List<Coupons> seckillList = couponsSeckillFeignClient.listSeckill().getData();
        if(seckillList != null && seckillList.size() > 0){
            for (Coupons seckill : seckillList) {
                redisTemplate.boundHashOps("secKillCoupons").put(seckill.getId(), seckill);
                // 根据优惠券的库存生成对应数量的“令牌”存储到Redis的队列中
                redisTemplate.boundListOps("secKillCouponsOver" + seckill.getId()).leftPushAll(pushIds(seckill.getStock()));
            }
        }
    }


    public Long[] pushIds(int len){
        Long[] ids = new Long[len];
        for (int i = 0; i <ids.length ; i++) {
            ids[i]=1L;
        }
        return ids;
    }
}
